package drds.binlog.filter.aviater;

import com.googlecode.aviator.AviatorEvaluator;
import com.googlecode.aviator.Expression;
import drds.binlog.filter.EventFilter;
import drds.binlog.filter.exception.BinlogFilterException;
import org.apache.commons.lang.StringUtils;

import java.util.*;

/**
 * 基于aviater进行tableName简单过滤计算，不支持正则匹配
 */
public class AviaterSimpleFilter implements EventFilter<String>
{

    private static final String SPLIT = ",";

    private static final String FILTER_EXPRESSION = "include(list,target)";

    private final Expression expression = AviatorEvaluator.compile(FILTER_EXPRESSION, true);

    private final List<String> list;

    public AviaterSimpleFilter(String filterExpression)
    {
        if (StringUtils.isEmpty(filterExpression))
        {
            list = new ArrayList<String>();
        } else
        {
            String[] strings = filterExpression.toLowerCase().split(SPLIT);
            list = Arrays.asList(strings);
        }
    }

    public boolean filter(String filtered) throws BinlogFilterException
    {
        if (list.isEmpty())
        {
            return true;
        }
        if (StringUtils.isEmpty(filtered))
        {
            return true;
        }
        Map<String, Object> env = new HashMap<String, Object>();
        env.put("list", list);
        env.put("target", filtered.toLowerCase());
        return (Boolean) expression.execute(env);
    }

}
